package com.ff.miaosha.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.Random;

public class Client {

    public static void main(String[] args){
        NioEventLoopGroup workGroup=new NioEventLoopGroup();
        Random random=new Random(System.currentTimeMillis());
        try {

            Bootstrap bootstrap=new Bootstrap();
            bootstrap.group(workGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline=socketChannel.pipeline();
                            pipeline.addLast(new IdleStateHandler(0,0,5));
                            pipeline.addLast(new LengthFieldBasedFrameDecoder(1024,0,4,-4,0));;
                            pipeline.addLast(new ClientHandler());
                        }
                    });

            Channel ch=bootstrap.remoteAddress("127.0.0.1",12345).connect().sync().channel();
            for (int i=0;i<1;i++){
                String content="client msg"+i;
                ByteBuf buf=ch.alloc().buffer();
                buf.writeInt(5+content.getBytes().length);
                buf.writeByte(CustomHeartbeatHander.CUSTOM_MSG);
                buf.writeBytes(content.getBytes());
                ch.writeAndFlush(buf);
                Thread.sleep(random.nextInt(2000));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            workGroup.shutdownGracefully();
        }
    }
}
